package com.ls.lsojcodesandbox.controller;

import com.ls.lsojcodesandbox.JavaDockerSandbox;
import com.ls.lsojcodesandbox.model.ExecuteCodeRequest;
import com.ls.lsojcodesandbox.model.ExecuteCodeResponse;
import com.ls.lsojcodesandbox.utils.JavaCodeSandboxTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.krb5.JavaxSecurityAuthKerberosAccess;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/")
public class MainController {
    public static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaDockerSandbox javaDockerSandbox;

    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        //身份认证
        String authHeader = httpServletRequest.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_REQUEST_SECRET.equals(authHeader)){
            httpServletResponse.setStatus(403);
            return null;
        }
        if(executeCodeRequest == null){
            throw new RuntimeException("参数为空");
        }
        return javaDockerSandbox.executeCode(executeCodeRequest);
    }
}
